package com.hjq.service.impl;

import com.hjq.entity.po.User;
import com.hjq.entity.vo.*;
import com.hjq.exception.ServiceException;
import com.hjq.mapper.UserMapper;
import com.hjq.service.UserService;
import com.hjq.utils.CurrentHolder;
import com.hjq.utils.JwtUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    // 创建BCryptPasswordEncoder实例
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    public UserInfoVO login(UserLoginVO user) {
        UserInfoVO login = userMapper.findByUsername(user);

        if(login != null){
            // 验证密码是否匹配
            if (!passwordEncoder.matches(user.getPassword(), login.getPassword())) {
                return null; // 密码不匹配
            }
            // token保存用户的id和username，生成token
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("id",login.getId());
            String jwt = JwtUtils.generateJwt(hashMap);
            // 添加生成的token到login对象
            login.setToken(jwt);
        }
        return login;
    }

    @Override
    public void register(UserRegisterVO userReg) {
        // 对密码进行加密
        String encodedPassword = passwordEncoder.encode(userReg.getPassword());
        userReg.setPassword(encodedPassword);
        User user = new User();
        BeanUtils.copyProperties(userReg, user);
        user.setStatus(1);
        user.setDelFlag(1);
        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());
        userMapper.add(user);
    }

    @Override
    public void delete(Integer id) {
        userMapper.deleteById(id);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserInfoForUpdateVO update(UserInfoForUpdateRequestVO updateRequestVO) {

        // 拷贝userInfoForUpdateVO到user
        User user = new User();
        BeanUtils.copyProperties(updateRequestVO, user);

        // 从本地变量中读取userId
        Long id = CurrentHolder.getCurrentId();
        user.setId(id);
        // 对密码进行判断
        if(user.getPassword() != null){
            // 判断旧密码是否正确
            User select = userMapper.findByIdForAll(user.getId());
            if(!passwordEncoder.matches(updateRequestVO.getPassword(), select.getPassword()))
                throw new ServiceException(400, "旧密码错误");
            // 对新密码加密
            String encodedPassword = passwordEncoder.encode(updateRequestVO.getNewPassword());
            // 加入user
            user.setPassword(encodedPassword);
        }

        user.setUpdatedAt(LocalDateTime.now());
        userMapper.update(user);
        // 更新完成后返回给前端更新后的用户信息
        UserInfoForUpdateVO newUser = userMapper.findById(id);
        return newUser;
    }

    @Override
    public Integer resetPassword(Long id) {
        String password = passwordEncoder.encode("123456");
        return userMapper.resetPassword(id,password);
    }
}
